package edu.wtbu.cs.bishe.service.impl;

import edu.wtbu.cs.bishe.domain.User;
import edu.wtbu.cs.bishe.mapper.UserMapper;
import edu.wtbu.cs.bishe.service.EmailService;
import edu.wtbu.cs.bishe.service.UserService;
import edu.wtbu.cs.bishe.utils.VerificationCodeGenerator;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;



@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final EmailService emailService;
//    private final PasswordEncoder passwordEncoder;

    @Async
    public void sendVerificationCode(String email) {
        User existingUser = userMapper.findByEmail(email);

        String code = VerificationCodeGenerator.generateCode(6);
        LocalDateTime expiryTime = LocalDateTime.now().plusMinutes(10);

        if (existingUser == null) {
            // 新用户
            User newUser = new User();
            newUser.setEmail(email);
            newUser.setEnabled(false);
            newUser.setVerificationCode(code);
            newUser.setCodeExpiryTime(expiryTime);
            newUser.setCodeAttempts(0);
            userMapper.insertUser(newUser);
        } else {
            // 已存在用户更新验证码
            existingUser.setVerificationCode(code);
            existingUser.setCodeExpiryTime(expiryTime);
            existingUser.setCodeAttempts(0);
            userMapper.updateUser(existingUser);
        }

        emailService.sendVerificationCode(email, code);
    }

    @Transactional
    public void verifyCode(String email, String code) {
        User user = userMapper.findByEmail(email);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        if (user.getCodeAttempts() >= 3) {
            throw new RuntimeException("验证尝试次数过多");
        }

        if (!code.equals(user.getVerificationCode())) {
            userMapper.incrementAttempts(email);
            throw new RuntimeException("验证码错误");
        }

        if (LocalDateTime.now().isAfter(user.getCodeExpiryTime())) {
            throw new RuntimeException("验证码已过期");
        }

        user.setEnabled(true);
        user.setVerificationCode(null);
        user.setCodeExpiryTime(null);
        userMapper.updateUser(user);
    }

    public void completeRegistration(String email, String password) {
        User user = userMapper.findByEmail(email);
        if (user == null || !user.getEnabled()) {
            throw new RuntimeException("请先完成邮箱验证");
        }

//        user.setPassword(passwordEncoder.encode(password));
        user.setPassword(password);
        userMapper.updateUserSelective(user);// 使用动态更新
    }
}